package com.zy.ivideo.service;

import com.zy.ivideo.entity.KSVideoEntity;
import com.zy.ivideo.entity.MultitypeVideoEntity;
import com.zy.ivideo.entity.ResponseEntity;
import com.zy.ivideo.entity.SimpleVideoEntity;
import com.zy.ivideo.repository.KSVideoRepository;
import com.zy.ivideo.repository.VideoMultitypeRepository;
import com.zy.ivideo.repository.VideoSimpleRepository;
import com.zy.ivideo.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.util.List;

@Service
public class SyncVideoService {
    @Autowired
    EntityManager entityManager;

    @Autowired
    KSVideoRepository ksVideoRepository;

    @Autowired
    VideoSimpleRepository videoSimpleRepository;

    @Autowired
    VideoMultitypeRepository videoMultitypeRepository;

    /**
     * 同步b_video数据到Simiple及mutil表中的videopath及videomainimg字段
     */
    public ResponseEntity<Boolean> sync(){
        try{
            List<KSVideoEntity> all = ksVideoRepository.findAll();
            List<SimpleVideoEntity> simpleAll = videoSimpleRepository.findAll();
            List<MultitypeVideoEntity> multiAll = videoMultitypeRepository.findAll();

            int min = Math.min(multiAll.size(),Math.min(all.size(),simpleAll.size()));

            int index=0;
            for (SimpleVideoEntity simpleVideoEntity:simpleAll){
                if (index>=all.size()){
                    index=0;
                }
                simpleVideoEntity.setVideopath(all.get(index).getVideopath());
                simpleVideoEntity.setVideomainimag(all.get(index).getVideomainimg());
                index++;
            }

            videoSimpleRepository.saveAll(simpleAll);

            for (MultitypeVideoEntity multitypeVideoEntity:multiAll){
                if (index>=all.size()){
                    index=0;
                }
                multitypeVideoEntity.setVideopath(all.get(index).getVideopath());
                multitypeVideoEntity.setVideomainimag(all.get(index).getVideomainimg());
                index++;
            }

            videoMultitypeRepository.saveAll(multiAll);
            return ResponseUtils.success(true);
        }catch (Exception ex){
            return ResponseUtils.failed(ex.getMessage());
        }
    }


}
